<script setup lang="tsx">
import {reactive, ref, unref} from 'vue'
import {delApi, queryApi, saveApi} from '@/api/role'
import {useTable} from '@/hooks/web/useTable'
import {useI18n} from '@/hooks/web/useI18n'
import {Table, TableColumn} from '@/components/Table'
import {ElTag} from 'element-plus'
import {Search} from '@/components/Search'
import {FormSchema} from '@/components/Form'
import {ContentWrap} from '@/components/ContentWrap'
import Write from './components/Write.vue'
import Detail from './components/Detail.vue'
import {Dialog} from '@/components/Dialog'
import {BaseButton} from '@/components/Button'

const {t} = useI18n()

const {tableRegister, tableState, tableMethods} = useTable({
  fetchDataApi: async () => {
    const {currentPage, pageSize} = tableState
    const res = await queryApi({
      page: unref(currentPage),
      size: unref(pageSize),
      ...unref(searchParams)
    })
    return {
      list: res.data.records || [],
      total: res.data.total
    }
  }
})

const {dataList, loading, total} = tableState
const {getList} = tableMethods

const tableColumns = reactive<TableColumn[]>([
  {
    field: 'index',
    label: t('userDemo.index'),
    type: 'index'
  },
  {
    field: 'name',
    label: t('role.roleName')
  },
  // {
  //   field: 'status',
  //   label: t('menu.status'),
  //   slots: {
  //     default: (data: any) => {
  //       return (
  //         <>
  //           <ElTag type={data.row.status === 0 ? 'danger' : 'success'}>
  //             {data.row.status === 1 ? t('userDemo.enable') : t('userDemo.disable')}
  //           </ElTag>
  //         </>
  //       )
  //     }
  //   }
  // },
  {
    field: 'createTime',
    label: t('tableDemo.displayTime')
  },
  {
    field: 'mark',
    label: t('userDemo.remark')
  },
  {
    field: 'action',
    label: t('userDemo.action'),
    width: 240,
    slots: {
      default: (data: any) => {
        const row = data.row
        return (
            <>
              <BaseButton type="primary" onClick={() => action(row, 'edit')}>
                {t('exampleDemo.edit')}
              </BaseButton>
              <BaseButton type="danger" onClick={() => remove(row.id)}>{t('exampleDemo.del')}</BaseButton>
            </>
        )
      }
    }
  }
])

const searchSchema = reactive<FormSchema[]>([
  {
    field: 'name',
    label: t('role.roleName'),
    component: 'Input'
  }
])

const searchParams = ref({})
const setSearchParams = (data: any) => {
  searchParams.value = data
  getList()
}

const dialogVisible = ref(false)
const dialogTitle = ref('')

const currentRow = ref()
const actionType = ref('')

const writeRef = ref<ComponentRef<typeof Write>>()

const saveLoading = ref(false)

const action = (row: any, type: string) => {
  dialogTitle.value = t(type === 'edit' ? 'exampleDemo.edit' : 'exampleDemo.detail')
  actionType.value = type
  currentRow.value = row
  dialogVisible.value = true
}

const AddAction = () => {
  dialogTitle.value = t('exampleDemo.add')
  currentRow.value = undefined
  dialogVisible.value = true
  actionType.value = ''
}

async function remove(id) {
  let res = await delApi([id])
  if (res.code == 0) {
    getList()
  }
}

const save = async () => {
  const write = unref(writeRef)
  const formData = await write?.submit()
  if (formData) {
    saveLoading.value = true
    try {
      let res = await saveApi(formData)
      saveLoading.value = false
      if (res.code == 0) {
        dialogVisible.value = false
        getList()
      }
    } catch (e) {
      console.log(e)
      saveLoading.value = false
    }
  }
}
</script>

<template>
  <ContentWrap>
    <Search :schema="searchSchema" @reset="setSearchParams" @search="setSearchParams"/>
    <div class="mb-10px">
      <BaseButton type="primary" @click="AddAction">{{ t('exampleDemo.add') }}</BaseButton>
    </div>
    <Table
        :columns="tableColumns"
        default-expand-all
        node-key="id"
        :data="dataList"
        :loading="loading"
        :pagination="{
        total
      }"
        @register="tableRegister"
    />
  </ContentWrap>

  <Dialog v-model="dialogVisible" :title="dialogTitle">
    <Write v-if="actionType !== 'detail'" ref="writeRef" :current-row="currentRow"/>
    <Detail v-else :current-row="currentRow"/>

    <template #footer>
      <BaseButton
          v-if="actionType !== 'detail'"
          type="primary"
          :loading="saveLoading"
          @click="save"
      >
        {{ t('exampleDemo.save') }}
      </BaseButton>
      <BaseButton @click="dialogVisible = false">{{ t('dialogDemo.close') }}</BaseButton>
    </template>
  </Dialog>
</template>
